package com.part.aspect;

import com.part.annotation.RequiredCache;
import com.part.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/10/20
 */
@Component
@Aspect
@Slf4j
public class CacheAspect {

    private Map<String, Object> cache = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.part.annotation.RequiredCache)")
    public void doCache() {
    }

    @Around("doCache()")
    public Object around(ProceedingJoinPoint jp) throws Throwable {
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Class<?> aClass = jp.getTarget().getClass();
        String methodName = signature.getMethod().getName();
        Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
        Method targetMethod = aClass.getDeclaredMethod(methodName, parameterTypes);
        RequiredCache requiredCache = targetMethod.getDeclaredAnnotation(RequiredCache.class);
        if (requiredCache == null || requiredCache.value() == null) {
            throw new ServiceException("缓存错误");
        }
        Object result = cache.get(requiredCache.value());
        if (result != null) {
            return result;
        }
        Object proceed = jp.proceed();
        cache.put(requiredCache.value(), proceed);
        return proceed;
    }


    private String cacheName(JoinPoint jp,Class<? extends Annotation> annotaClass) throws NoSuchMethodException, IllegalAccessException, InstantiationException {
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Class<?> aClass = jp.getTarget().getClass();
        Method declaredMethod = aClass.getDeclaredMethod(signature.getName(), signature.getParameterTypes());
        Annotation annotation1 = declaredMethod.getAnnotation(annotaClass);
        String name="";
        if (annotation1 instanceof RequiredCache){
            name=((RequiredCache) annotation1).value();
        }
        return name;
    }
}
